//
//  ZyaReportWebController.swift
//  SlaughterClient
//
//  Created by qiuxiankai on 2016/12/23.
//  Copyright © 2016年 四美达. All rights reserved.
//

import UIKit
import WebKit
import IQKeyboardManagerSwift
import SVProgressHUD
class ZyaReportWebController: UIViewController, WKNavigationDelegate, WKUIDelegate {
   
    
    var loadUrl = ""
    var startDate = today_pre_s(1080)
    var endDate = today_s()
    var commonWebview = WKWebView()
    
    
    fileprivate lazy var progress: UIProgressView = {
        let progress = UIProgressView()
        progress.frame = CGRect(x: 0, y: 0, width: self.view.ks_width, height: 5)
        progress.backgroundColor = #colorLiteral(red: 0.1803921569, green: 0.1960784314, blue: 0.568627451, alpha: 1)
        self.view.addSubview(progress)
        return progress
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        //title
        navigationItem.title = "日销售对账表"
  
     
        let config = WKWebViewConfiguration()
        config.preferences = WKPreferences()
        config.preferences.minimumFontSize = 18
        config.processPool = WKProcessPool()
        
        commonWebview = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), configuration: config)
        //添加webView
        commonWebview.navigationDelegate = self
        commonWebview.uiDelegate = self
        view.addSubview(commonWebview)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(searchAction(_:)))
        
       SVProgressHUD.show()
        commonWebview.load(URLRequest(url: URL(string: joinUrl())!))
 

        
        
        //进度条
        commonWebview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        
    }
 
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            print(commonWebview.estimatedProgress)
            progress.progress = Float(commonWebview.estimatedProgress)
        }
        
        if !commonWebview.isLoading {
            UIView.animate(withDuration: 0.55, animations: { () -> Void in
                self.progress.alpha = 0.0;
            })
        }
        
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
        UIView.animate(withDuration: 0.55, animations: { () -> Void in
            self.progress.alpha = 0.0;
        })
        let str = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"
        webView.evaluateJavaScript(str) { (response, error) in
            
        }
        let str2 = "javascript:var imgs = document.getElementsByTagName('img');for(var i = 0; i<imgs.length; i++){imgs[i].style.width = '90%';imgs[i].style.height = 'auto';}"
        webView.evaluateJavaScript(str2) { (response, error) in
            
        }
        
    }
    
    deinit {
        print("网页显示销毁")
        commonWebview.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @objc fileprivate func searchAction(_ sender: Any) {
        let alert = KSAlertView()
        let txt0 = alert.addDatePicker(withLabel: "开始日期", action: nil)
        let txt1 = alert.addDatePicker(withLabel: "结束日期", action: nil)
        txt0.text = self.startDate
        txt1.text = self.endDate
        _ = alert.addButton("查询") { [weak self] in
            self!.startDate = txt0.text!
            self!.endDate = txt1.text!


            self!.commonWebview.load(URLRequest(url: URL(string: self!.joinUrl())!))


        }
        alert.show("查询条件", duration: 0.2, completeText: nil)

    }
    func joinUrl() -> String {
        return  "\(reportUrl())\(TOKEN)?reportlet=sale/kh_day_dz.cpt&kf_id=\(USERINFO.usrid!)&begin_day=\(self.startDate)&end_day=\(self.endDate)&session=\(TOKEN)"
    }
    //    https://khtest.zhuok.com.cn/khw/print/PrintApp?formlet=reportlet&reportlet=sale/kh_day_dz.cpt&kf_id=17615435&begin_day=2022-03-31&end_day=2022-03-31&session=05DFC87B2AD3894BD2810B4A879F995458DC144146519BD621B6E1A2573325B4389A26CD14824019&cached=app&ly=app
}

// MARK: navigationDelegate
extension ZyaReportWebController {
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("bug")
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("start")
    }
}




